package com.zhoubg.spring.transaction.demo1.service.impl;

import com.zhoubg.spring.transaction.demo1.dao.AccountDao;
import com.zhoubg.spring.transaction.demo1.service.AccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;

/**
 * Create by Zhoubg at 2017/10/18
 */
@Service
public class AccountServiceImpl implements AccountService{

    @Resource
    private AccountDao accountDaoImpl;
    @Resource
    private TransactionTemplate transactionTemplate;  //注入事务管理的模板

    /**
     * @param out	:转出账号
     * @param in	:转入账号
     * @param money	:转账金额
     */
    public void transfer(final String out,final String in,final Double money) {

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                 try { //具体业务代码
                    accountDaoImpl.outMoney(out,money);
                    //int i = 1/0;
                    accountDaoImpl.inMoney(in,money);
                }catch (Exception e){
                    status.setRollbackOnly(); //设置回滚
                    e.printStackTrace();
                }
            }
        });
    }
}
